// 获取DOM元素
const chatMessages = document.getElementById('chat-messages');
const userInput = document.getElementById('user-input');
const sendButton = document.getElementById('send-button');

// 发送按钮点击事件处理函数
sendButton.addEventListener('click', async () => {
    const question = userInput.value;
    if (question.trim() === '') {
        return;
    }
    // 将用户输入的消息添加到聊天框展示
    displayMessage('用户', question);
    userInput.value = '';

    try {
        // 发送POST请求到后端的问答接口
        const response = await fetch('http://localhost:8012/v1/chat/completions', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                "messages": [
                    {
                        "role": "user",
                        "content": question
                    }
                ],
                "stream": false
            })
        });

        const data = await response.json();
        const answer = data.choices[0].message.content;
        // 将后端返回的回答添加到聊天框展示
        displayMessage('助手', answer);
    } catch (error) {
        console.error('请求出错:', error);
        displayMessage('系统', '请求出现错误，请稍后再试');
    }
});

function displayMessage(sender, message) {
    const messageDiv = document.createElement('div');
    messageDiv.innerHTML = `<strong>${sender}:</strong> ${message}`;
    chatMessages.appendChild(messageDiv);
}